<template>
    <div class="modal fade" id="uploadExcelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          	<div class="modal-header">
            	<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            	<h4 class="modal-title" id="myModalLabel">批量导入</h4>
          	</div>
          	<div class="modal-body">
          	 	<div class="form-horizontal">
	                <div class="form-group">
	                    <label for="" class="col-sm-4 control-label">选择附件：</label>
	                    <div class="col-sm-8">
	                       <input type="file" class="form-control" @change="onFileChange" name="fileName" id="fileName">
	                    </div>
	                </div>
	                <div class="form-group" style="margin-bottom:0px">
	                	<label for="" class="col-sm-4 control-label">&nbsp;</label>
	                	<div class="col-sm-8">
	                		<a v-bind:href="importOrgTempUrl">模板下载</a>
	                		<a style="margin-left: 50px;" v-show="errorBtnShow" @click="importError">错误信息下载</a>
	                	</div>
	                </div>
	            </div>
          	</div>
          	<div class="modal-footer">
            	<!--<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>-->
            	<button type="button" class="btn checkedBtn" v-show="saveBtnShow" @click="ajaxfile">导入</button>
          	</div>
        </div>
      </div>
    </div>
</template>

<script>
	export default{
		//接收父组件的绑定值
		props: ["excelModal"],
		data() {
			return {
				errorBtnShow: false,
				saveBtnShow: true,
				fileUrl: '',
				fileName: '',
				parentId: this.excelModal.orgId,
				userId: window.localStorage.getItem("4_userId"),
				importOrgTempUrl: '',
				impId: ''
			}
		},
		watch: {
			//监听父组件绑定值是否改变
			excelModal: {
				handler: function(val, oldVal){
					this.initTempUrl();
					this.errorBtnShow = false; 
				},
				//深层监听，当位对象时，若设为true，属性变更时即可触发，若为false，属性无法监听到
				deep: true
			}
		},
		mounted: function() {
			//this.initTempUrl();
		},
		methods: {
			initModal () {
				var file = document.getElementById('fileName');
				file.value = '';
			},
			initTempUrl() {
				if(this.excelModal.optType == '1'){
					this.importOrgTempUrl = this.utilHelper.importOrgTempUrl;
				}else if(this.excelModal.optType == '2'){
					this.importOrgTempUrl = this.utilHelper.importUserTempUrl;
				}
			},
			//创建附件对象
			onFileChange(e) {
		        var files = e.target.files || e.dataTransfer.files;
		        if (!files.length)
		           return;
                var size = files[0].size;
                if(size > 3145728){
                    layer.msg("图片大小不能超过3M");
                    return;
                }
		        this.createFile(files[0]);
		    },
		    createFile(file) {
		        var _self = this;
				var reader = new FileReader();
		        reader.readAsDataURL(file);
		        reader.onload = function(e){  
		            _self.fileUrl = e.target.result;
		        };  
		    },
		    //将base64转换blob
		    dataURLtoBlob(dataUrl) {
			    var arr = dataUrl.split(','), 
			        mime = arr[0].match(/:(.*?);/)[1],
			        bstr = atob(arr[1]), 
			        n = bstr.length, 
			        u8arr = new Uint8Array(n);
			    while (n--) {
			        u8arr[n] = bstr.charCodeAt(n);
			    }
			    return new Blob([u8arr], { type: mime });
		    },
			//上传excel
		    ajaxfile(){
		    	var _self = this;
		    	if(_self.fileUrl == null || _self.fileUrl == ""){
		    		layer.msg("请选择需要导入的excel");
		    		return false;
		    	}
		    	var fileName = $("#fileName").val();
		    	var suffix = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length);
		    	if(suffix != "xls" && suffix != "xlsx"){
		    		layer.msg("请选择正确的excel");
		    		return false;
		    	}
		    	var myForm = new FormData();     //创建formdata
				var blobBin = _self.dataURLtoBlob(_self.fileUrl);   //base64转换blob
				myForm.append(suffix, blobBin);    //向formData添加blob数据
				myForm.append("parentId", this.excelModal.orgId);
				myForm.append("optType", this.excelModal.optType); 
				myForm.append("userId", _self.userId);
		    	var url = _self.utilHelper.apiUrl+'/api/importOrg';
		    	layer.load(0, {shade: false}); //弹出加载层
                _self.$http.post(url,myForm).then((response)=>{
                	layer.closeAll('loading'); //关闭加载层
                	var data = response.body.resData;
                	if(data.result == "1"){
                		//子组件向父组件传递信号: 调用父组件中对子组件的监听
						_self.$emit('saveExcelListener');
                		if(data.uuid != null){
							_self.errorBtnShow = true;
							_self.impId = data.uuid;
						}else{
							if(data.uuid == null){
								//关闭弹出层
								$('#uploadExcelModal').modal('hide');
							}
						}
                	}
              		layer.msg(data.resultMsg, {
							time: 4000
					});   	
                });
		    },
		    importError() {
		    	var _self = this;
		    	var params = {};
		    	params.userId = _self.userId;
		    	params.impId = _self.impId;
		    	if(_self.excelModal.optType == "1"){
		    		params.importType = '1'
		    		
		    	}else if(_self.excelModal.optType == "2"){
		    		params.importType = '2'
		    	}
		    	window.location.href = _self.utilHelper.apiUrl+'/api/exportImportErrorMsg?params.userId='+params.userId+'&params.impId='+params.impId +'&params.importType='+params.importType+'&params.loginType=4';
		    }
		}
	}
	
</script>